using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;

namespace ArchSoft
{
    public class AttachTitle
    {
        string _sourcePath;

        public AttachTitle(string source)
        {
            _sourcePath = source;          
        }

        public bool DeleteTarget()
        {
            try
            {
                DirectoryInfo source = new DirectoryInfo(_sourcePath);
                foreach (DirectoryInfo subDir in source.GetDirectories())
                {
                    foreach (FileInfo file in subDir.GetFiles())
                    {
                        if (!file.Extension.Equals(".dwg") && !file.Extension.Equals(".dwt"))
                        {
                            file.Delete();
                        }
                    }
                }
                return true;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; }
        }

        private void DeleteTempFile()
        {
            DirectoryInfo issueWindow = new DirectoryInfo(_sourcePath);
            foreach (FileInfo adrawing in issueWindow.GetFiles())
            {
                    adrawing.Delete();
            }

            foreach (DirectoryInfo dir in issueWindow.GetDirectories())
            {                
                if (dir.Name.ToLower().Contains("reference"))
                {
                    dir.Delete(true);
                }
                else
                {
                    foreach (FileInfo adrawing in dir.GetFiles())
                    {
                        if (!adrawing.Extension.Contains("dwg") && !adrawing.Extension.Contains("dwt"))
                        {
                            adrawing.Delete();
                        }
                    }
                }
            }
        }

        public string GenerateScriptFile(string ChildWindow, List<string> drawings)
        {          
            string sourceWindow = _sourcePath + Path.DirectorySeparatorChar + ChildWindow;
          
            // Generate script
            string tempFileName = _sourcePath + @"\" + Guid.NewGuid().ToString() + ".scr";

            FileStream scriptFile = File.Open(tempFileName, FileMode.CreateNew);
            StreamWriter wr = new StreamWriter(scriptFile);

            wr.WriteLine("filedia 0");

            for (int i = 0; i < drawings.Count - 1; i++)
            {
                ScriptForUpdLayout(wr, false, sourceWindow + "\\" + drawings[i]);
            }
            ScriptForUpdLayout(wr, true, sourceWindow + "\\" + drawings[drawings.Count - 1]);

            wr.WriteLine("filedia 1");
            wr.WriteLine("quit");
            wr.Flush();
            wr.Dispose();

            scriptFile.Close();
            scriptFile.Dispose();
            return tempFileName;
        }

        public string GenerateScriptFile(string ChildWindow)
        {
            // Collect drawings
            List<string> issuedDrawings = new List<string>();
            
            DirectoryInfo issueWindow = new DirectoryInfo(_sourcePath);
            foreach (DirectoryInfo dir in issueWindow.GetDirectories())
            {
                if (dir.Name == "Xref")
                    continue;
                if ((ChildWindow != "") & (dir.Name != ChildWindow))
                    continue;
                foreach (FileInfo adrawing in dir.GetFiles())
                    issuedDrawings.Add(adrawing.FullName);
            }

            // Generate script

            string tempFileName = _sourcePath + @"\" + Guid.NewGuid().ToString() + ".scr";

            FileStream scriptFile = File.Open(tempFileName, FileMode.CreateNew);
            StreamWriter wr = new StreamWriter(scriptFile);

            wr.WriteLine("filedia 0");
            
             
            for (int i = 0; i < issuedDrawings.Count - 1; i++)
            {
                ScriptForUpdLayout(wr, false, issuedDrawings[i]);
            }
            ScriptForUpdLayout(wr, true, issuedDrawings[issuedDrawings.Count - 1]);

            wr.WriteLine("filedia 1");
            wr.WriteLine("quit");
            wr.Flush();
            wr.Dispose();

            scriptFile.Close();
            scriptFile.Dispose();
            return tempFileName;          
        }       

        public string RunSciptFile(string filePath)
        {
            AutocadHelper helper = AutocadHelper.Instance;
            return helper.RunAutoCadScript(filePath, true);        
        }

        public string Process(string childWindow, List<string> drawings)
        {
            string str = "";

            bool tpd = DeleteTarget(); if (!tpd) { return ""; }
            
            string scriptFile;
            if (drawings == null)
                scriptFile = GenerateScriptFile(childWindow);
            else
                scriptFile = GenerateScriptFile(childWindow, drawings);

            str = RunSciptFile(scriptFile);
            DeleteTempFile();
            return str;
        }

        public string Process(string childWindow)
        {
            return Process(childWindow, null);
        }

        public string Process()
        {
            return Process(string.Empty, null);
        }        

        public void ScriptForUpdLayout(StreamWriter wr, bool lastDrawing, string fileName) //, string FileCode
        {            
            wr.WriteLine("open \"" + fileName + "\"");           
            wr.WriteLine("TILEMODE");
            wr.WriteLine("0");
            wr.WriteLine("-XREF");
            wr.WriteLine("A");
            wr.WriteLine("\"" + "..\\Xref\\A_Title Block.dwg" + "\"");
            wr.WriteLine("0,0");
            wr.WriteLine("");
            wr.WriteLine("");
            wr.WriteLine("");
            wr.WriteLine("QSAVE");
            if (!lastDrawing)
            {
                wr.WriteLine("Close");
            }
        }
    }
}
